<?php

namespace App\Jobs;

use App\Models\TourOrder;
use App\Models\TourTuan;
use App\Models\TourTuanData;
use Illuminate\Support\Facades\DB;

class TourTuanJob extends Job
{
    protected $job_name ='TourTuanJob';
    private $runtime = null;
    private $rows_per_loop =10;

    /**
     * 创建一个新的任务实例。
     *
     * @param $time 启动时间
     */
    public function __construct($time)
    {
        parent::__construct();
        $this->runtime = $time;
    }

    /**
     * 运行任务。
     *
     * @return void
     */
    public function handle()
    {
        //业务说明：
        // 定时取消未成功的团

        $this->logger->info('========start======');
        $this->logger->info('runtime:'.$this->runtime);
        $this->logger->info('runtime2:'.gmtime());
        $timeline = $this->runtime;
        $this->FailureTourTuan($timeline);//组团失败

        $this->logger->info('========end======');
    }

    private function FailureTourTuan($timeline){

        //组团失败
        $this->logger->info('========团失败======');

        $i =1;//批次
        $tuans =null;

        while(true){

            $this->logger->info('【第'.$i.'批】');

            /* 超时未成功的团 */
            $tuans = TourTuan::where('state',TUAN_STATE_WAITE)
                ->where(function($query) use($timeline) {
                    $query->where('end_time', '<=', $timeline)
                        ->OrWhere('copy_tour_date', '<=', $timeline);
                })
                ->where('rest_copies','>', 0)
                ->select('tuan_id')
                ->skip(0)->take($this->rows_per_loop)
                ->get();

            $this->logger->info('总数:'.count($tuans));

            if(count($tuans)==0){
                break;
            }

            $tuan_ids =array_pluck($tuans,'tuan_id');

            $this->logger->info('执行: '.json_encode($tuan_ids));

            DB::beginTransaction();

            try{

                //组团状态更新
                DB::table('tour_tuan')
                    ->whereIn('tuan_id',$tuan_ids)
                    ->update(['state'=>TUAN_STATE_FAILURE,
                        'failure_reason'=>'指定时间内人数不足系统自动取消']);

                //退款订单队列
                $order_ids =TourTuanData::whereIn('tuan_id',$tuan_ids)->where('state',TUAN_DATA_STATE_SUCCESS)->lists('order_id');

                if($order_ids){
                    $order_ids =TourOrder::whereIn('order_id',$order_ids)
                        ->where('status',TOUR_ORDER_ACCEPTED)
                        ->orWhere('status', TOUR_ORDER_SUBMITTED)
                        ->lists('order_id');

                    //tourtuan_refund_queue  线路团失败退款队列
                    foreach($order_ids as $order_id){
                        DB::table('tour_refund_queue')->insert(['order_id'=>$order_id,'status'=>0]);
                    }
                }

                DB::commit();

            } catch(\Exception $e){
                DB::rollback();
                $this->logger->info('error msg:'. $e->getMessage() . ' trace:'. $e->getTraceAsString());
            }

            if(count($tuans)<$this->rows_per_loop){
                break;
            }

            $i++;

        }

    }

}
